package com.haotunet.app.goldtreasure.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.haotunet.app.goldtreasure.R;
import com.haotunet.app.goldtreasure.activity.DynamicDetailActivity;
import com.haotunet.app.goldtreasure.activity.LoginActivity;
import com.haotunet.app.goldtreasure.activity.RegisterActivity;
import com.haotunet.app.goldtreasure.activity.SettingActivity;
import com.haotunet.app.goldtreasure.db.DBOpenHelper;
import com.haotunet.app.goldtreasure.model.BaseModel;
import com.haotunet.app.goldtreasure.model.MsgInfo;
import com.haotunet.app.goldtreasure.model.PersonalInfo;
import com.haotunet.app.goldtreasure.net.ActionUtil;
import com.haotunet.app.goldtreasure.net.UrlUtil;
import com.haotunet.app.goldtreasure.other.Interface.OnPassBackListener;
import com.haotunet.app.goldtreasure.utils.ActivityUtils;
import com.haotunet.app.goldtreasure.utils.NetworkUtil;
import com.haotunet.app.goldtreasure.utils.ShareStore;
import com.haotunet.app.goldtreasure.utils.Strs;
import com.haotunet.app.goldtreasure.utils.UIHelper;
import com.haotunet.app.goldtreasure.utils.Utils;
import com.haotunet.app.goldtreasure.views.TitleView;
import com.haotunet.app.pulltorefresh.PullToRefreshLayout;
import com.haotunet.app.pulltorefresh.PullToRefreshLayout.OnRefreshListener;

public class PersonalCenterFragment extends BaseFragment implements OnClickListener {
    private TitleView mTitleView;
    private PullToRefreshLayout mfreshLayout;
    private RelativeLayout mTransRecord;
    private LinearLayout mRedPacketLayout;
    private LinearLayout mGoldCoins;
    private LinearLayout mCoupon;
    private LinearLayout mInvite;
    private RelativeLayout mSetting;
    private Button btnLogin;
    private Button btnRegister;
    private ImageView mAssetsStatus;
    private RelativeLayout tvMyWallet, tvMyVault;
    private TextView tvSell, tvDeposit, tvPick;
    private TextView mYesterdayProfit, mTotalProfit, mTotalAssets, mWalletMoney, mVaultGrams, mCoinNum, mCouponNum,
            mInviteCode, mRedPacketTxt;
    /**
     * 标志位，标志已经初始化完成
     */
    private boolean isPrepared;
    /**
     * 是否已被加载过一次，第二次就不再去请求数据了
     */

    private View view;
    private FrameLayout mLayout;
    private ShareStore shareStore;
    private boolean isLogin;
    private DBOpenHelper helper;
    private final int GET_PERSONAL_PAGE_INFO_SUCCESS = 2;
    private PersonalInfo personalInfo;
    private String coinNums;

    private Handler handle = new Handler() {

        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case GET_PERSONAL_PAGE_INFO_SUCCESS:
                    personalInfo = (PersonalInfo) msg.obj;
                    int isHadBankCard = personalInfo.getIsHadBankCard();
                    int isHadTradingPassword = personalInfo.getIsHadTradingPassword();
                    shareStore.putInt(Strs.IS_HAD_TRADING_PWD, isHadTradingPassword);
                    shareStore.putInt(Strs.IS_HAD_BANK_CARD, isHadBankCard);
                    shareStore.putString(Strs.HEAD_IMAGE, personalInfo.getHeadImage());
                    if (personalInfo.getIsShowG20Order() != null) {
                        shareStore.putBoolean(Strs.IS_SHOW_G20, personalInfo.getIsShowG20Order());
                    }
                    shareStore.commit();
                    mTitleView.getTitletextView().setText(Utils.hideMidFourPhoneNum(personalInfo.getUserName()));
                    if (shareStore.getBoolean(Strs.ASSETS_STATUS, true)) {
                        displayUserInfo();
                    } else {
                        hideUserInfo();
                    }
                    coinNums = personalInfo.getCoinCount();
                    mCoinNum.setText(coinNums + getString(R.string.coins_unit));
                    mRedPacketTxt.setText(personalInfo.getRedPacketBalance() + "元");
                    mCouponNum.setText(personalInfo.getCouponCount() + getString(R.string.coupon_unit));
                    mInviteCode.setText(personalInfo.getInvitationCode());

                    break;
                default:
                    break;
            }
        }

    };
    private View unloginView;

    public static PersonalCenterFragment newInstance() {
        return new PersonalCenterFragment();
    }

    public PersonalCenterFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_personal_center, container, false);
        helper = new DBOpenHelper(getActivity());
        isPrepared = true;
        shareStore = new ShareStore(getActivity());
        initView();
        getUnReadMsg();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        isLogin = shareStore.getBoolean(Strs.IS_LOGIN, false);
        if (isLogin) {
            getPersonalPageInfo("");
        }
    }

    private void initView() {
        unloginView = getActivity().getLayoutInflater().inflate(R.layout.unlogin_popup_view, null);
        btnLogin = (Button) unloginView.findViewById(R.id.btn_login);
        btnRegister = (Button) unloginView.findViewById(R.id.btn_register);
        mTitleView = (TitleView) view.findViewById(R.id.title_view_personal_page);
        mTitleView.getTitletextView().setVisibility(View.VISIBLE);
        mTitleView.getTitletextView().setText(getString(R.string.main_menu3_txt));
        mTitleView.getGuideView().setVisibility(View.VISIBLE);
        mTitleView.getGuideView().setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                ActivityUtils.gotoNewGuideLines(getActivity());
            }
        });
        mTitleView.getNotificationView().setVisibility(View.VISIBLE);
        mTitleView.getNotificationView().setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), DynamicDetailActivity.class);
                intent.putExtra("activityUrl", UrlUtil.MESSAGE_CENTER);
                intent.putExtra("type", 0);
                startActivityForResult(intent, 6);
            }
        });

        mLayout = (FrameLayout) view.findViewById(R.id.frame_unlogin);
        mfreshLayout = (PullToRefreshLayout) view.findViewById(R.id.id_swipe_ly);
        mfreshLayout.setOnRefreshListener(new OnRefreshListener() {

            @Override
            public void onRefresh(final PullToRefreshLayout pullToRefreshLayout) {
                if (!isLogin) {
                    mfreshLayout.refreshFinish(PullToRefreshLayout.FAIL);
                    UIHelper.showToast(getActivity(), getString(R.string.please_login));
                } else {
                    getPersonalPageInfo("refresh");
                }
            }

            @Override
            public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {

            }
        });

        mAssetsStatus = (ImageView) view.findViewById(R.id.iv_assets_status);
        mTransRecord = (RelativeLayout) view.findViewById(R.id.rl_transaction_record);
        mRedPacketLayout = (LinearLayout) view.findViewById(R.id.red_packet_layout);
        mGoldCoins = (LinearLayout) view.findViewById(R.id.ll_gold_coin);
        mCoupon = (LinearLayout) view.findViewById(R.id.ll_coupon);
        mInvite = (LinearLayout) view.findViewById(R.id.ll_invite);
        mSetting = (RelativeLayout) view.findViewById(R.id.rl_setting);
        tvMyVault = (RelativeLayout) view.findViewById(R.id.rl_my_vault);
        tvMyWallet = (RelativeLayout) view.findViewById(R.id.rl_my_wallet);
        tvSell = (TextView) view.findViewById(R.id.tv_sell_gold);
        tvDeposit = (TextView) view.findViewById(R.id.tv_deposit_gold);
        tvPick = (TextView) view.findViewById(R.id.tv_pick_gold);
        mRedPacketTxt = (TextView) view.findViewById(R.id.red_packet_txt);
        mCoinNum = (TextView) view.findViewById(R.id.coin_num);
        mCouponNum = (TextView) view.findViewById(R.id.coupon_num);
        mTotalAssets = (TextView) view.findViewById(R.id.my_total_assets);
        mTotalProfit = (TextView) view.findViewById(R.id.total_profit);
        mYesterdayProfit = (TextView) view.findViewById(R.id.yesterday_profit);
        mWalletMoney = (TextView) view.findViewById(R.id.txt_my_wallet);
        mVaultGrams = (TextView) view.findViewById(R.id.txt_my_vault);
        mInviteCode = (TextView) view.findViewById(R.id.invite_code);
        setListener();

    }

    private void setListener() {
        btnLogin.setOnClickListener(this);
        btnRegister.setOnClickListener(this);
        mAssetsStatus.setOnClickListener(this);
        mTransRecord.setOnClickListener(this);
        mGoldCoins.setOnClickListener(this);
        mCoupon.setOnClickListener(this);
        mInvite.setOnClickListener(this);
        mRedPacketLayout.setOnClickListener(this);
        mSetting.setOnClickListener(this);
        tvMyWallet.setOnClickListener(this);
        tvMyVault.setOnClickListener(this);
        tvSell.setOnClickListener(this);
        tvDeposit.setOnClickListener(this);
        tvPick.setOnClickListener(this);
    }

    private void getPersonalPageInfo(final String action) {
        ActionUtil actionUtil = new ActionUtil(getActivity());
        actionUtil.getPersonalPageInfo();
        actionUtil.setOnPassBackListener(new OnPassBackListener() {

            @Override
            public void passBack(BaseModel model) {
                if (!isActivityAvailable()) {
                    return;
                }
                PersonalInfo pInfo = (PersonalInfo) model;
                if (pInfo == null) {
                    if (action.equals("refresh")) {
                        mfreshLayout.refreshFinish(PullToRefreshLayout.FAIL);
                    }
                    UIHelper.showToast(getActivity(), getString(R.string.rank_fail));
                    return;
                }
                if (pInfo.getErrorMsg() != null) {
                    if (action.equals("refresh")) {
                        mfreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
                    }
                    if (pInfo.getErrorCode().equals(Strs.EXTRUSION_SIGN_IN)) {
                        ActivityUtils.forceQuit(getActivity(), getString(R.string.crowding_in_tips_txt));
                    } else if (pInfo.getErrorCode().equals(Strs.TOKEN_EXPIRATION)) {
                        ActivityUtils.forceQuit(getActivity(), getString(R.string.token_expired_tips_txt));
                    } else {
                        UIHelper.showToast(getActivity(), pInfo.getErrorMsg());
                    }
                } else {
                    if (action.equals("refresh")) {
                        mfreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
                    }
                    Message msg = new Message();
                    msg.what = GET_PERSONAL_PAGE_INFO_SUCCESS;
                    msg.obj = pInfo;
                    handle.sendMessage(msg);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login:
                Intent intent = new Intent(getActivity(), LoginActivity.class);
                startActivityForResult(intent, 1);
                break;
            case R.id.btn_register:
                Intent registerIntent = new Intent(getActivity(), RegisterActivity.class);
                startActivity(registerIntent);
                break;
            case R.id.iv_assets_status:
                if (shareStore.getBoolean(Strs.ASSETS_STATUS, true)) {
                    shareStore.putBoolean(Strs.ASSETS_STATUS, false);
                    shareStore.commit();
                    mAssetsStatus.setSelected(true);
                    hideUserInfo();
                } else {
                    shareStore.putBoolean(Strs.ASSETS_STATUS, true);
                    shareStore.commit();
                    mAssetsStatus.setSelected(false);
                    displayUserInfo();
                }
                break;
            case R.id.tv_sell_gold:
                if (NetworkUtil.isConnected(getActivity())) {
                    if (isLogin) {
                        ActivityUtils.gotoSellGold(getActivity());
                    } else {
                        ActivityUtils.gotoLogin(getActivity());
                    }
                } else {
                    UIHelper.showToast(getActivity(), getString(R.string.rank_fail));
                }
                break;
            case R.id.tv_deposit_gold:
                if (NetworkUtil.isConnected(getActivity())) {
                    if (isLogin) {
                        if (helper.getRealName().equals("")) {
                            UIHelper.showRemindDialog(getActivity(), "您尚未实名认证,暂不支持此项服务!");
                            return;
                        }
                        ActivityUtils.gotoDepositGold(getActivity());
                    } else {
                        ActivityUtils.gotoLogin(getActivity());
                    }
                } else {
                    UIHelper.showToast(getActivity(), getString(R.string.rank_fail));
                }
                break;
            case R.id.tv_pick_gold:
                if (NetworkUtil.isConnected(getActivity())) {
                    if (isLogin) {
                        ActivityUtils.gotoPickGold(getActivity(), "0");
                    } else {
                        ActivityUtils.gotoLogin(getActivity());
                    }
                } else {
                    UIHelper.showToast(getActivity(), getString(R.string.rank_fail));
                }

                break;
            case R.id.rl_transaction_record:
                if (NetworkUtil.isConnected(getActivity())) {
                    if (isLogin) {
                        ActivityUtils.gotoTransRecord(getActivity(), "personalFragment");
                    } else {
                        ActivityUtils.gotoLogin(getActivity());
                    }
                } else {
                    UIHelper.showToast(getActivity(), getString(R.string.rank_fail));
                }
                break;
            case R.id.red_packet_layout:
                ActivityUtils.gotoRedPacket(getActivity());
                break;
            case R.id.ll_gold_coin:
                if (NetworkUtil.isConnected(getActivity())) {
                    if (isLogin) {
                        ActivityUtils.gotoGCoinDetail(getActivity(), coinNums);
                    } else {
                        ActivityUtils.gotoLogin(getActivity());
                    }
                } else {
                    UIHelper.showToast(getActivity(), getString(R.string.rank_fail));
                }
                break;
            case R.id.ll_coupon:
                if (NetworkUtil.isConnected(getActivity())) {
                    if (isLogin) {
                        ActivityUtils.gotoDiscount(getActivity());
                    } else {
                        ActivityUtils.gotoLogin(getActivity());
                    }
                } else {
                    UIHelper.showToast(getActivity(), getString(R.string.rank_fail));
                }
                break;

            case R.id.ll_invite:
                if (NetworkUtil.isConnected(getActivity())) {
                    if (isLogin) {
                        ActivityUtils.gotoDynamicDetail(getActivity(), UrlUtil.INVITE_URL, 0);
                    } else {
                        ActivityUtils.gotoLogin(getActivity());
                    }
                } else {
                    UIHelper.showToast(getActivity(), getString(R.string.rank_fail));
                }
                break;
            case R.id.rl_setting:
                if (NetworkUtil.isConnected(getActivity())) {
                    if (isLogin) {
                        Intent settingIntent = new Intent(getActivity(), SettingActivity.class);
                        startActivityForResult(settingIntent, 2);
                    } else {
                        ActivityUtils.gotoLogin(getActivity());
                    }
                } else {
                    UIHelper.showToast(getActivity(), getString(R.string.rank_fail));
                }
                break;

            case R.id.rl_my_wallet:
                if (NetworkUtil.isConnected(getActivity())) {
                    ActivityUtils.gotoMyWallet(getActivity());
                } else {
                    UIHelper.showToast(getActivity(), getString(R.string.rank_fail));
                }
                break;
            case R.id.rl_my_vault:
                if (NetworkUtil.isConnected(getActivity())) {
                    ActivityUtils.gotoMyVault(getActivity());
                } else {
                    UIHelper.showToast(getActivity(), getString(R.string.rank_fail));
                }
                break;
            default:
                break;
        }
    }

    private void displayUserInfo() {
        if (personalInfo != null) {
            mTotalAssets.setText(personalInfo.getTotalAssets());
            mWalletMoney.setText(personalInfo.getBalance());
            mVaultGrams.setText(personalInfo.getTotalGold());
            mTotalProfit.setText(personalInfo.getTotalProfit());
            mYesterdayProfit.setText(personalInfo.getYesterdayProfit());
        }
    }

    private void hideUserInfo() {
        mTotalAssets.setText("****");
        mWalletMoney.setText("****");
        mVaultGrams.setText("****");
        mTotalProfit.setText("****");
        mYesterdayProfit.setText("****");
    }


    @SuppressWarnings("static-access")
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == getActivity().RESULT_OK) {
            showUnLoginDialog();
        }
        if (requestCode == 2 && resultCode == getActivity().RESULT_OK) {
            setUnloginInfo();
            mLayout.addView(unloginView);
        }
        if (requestCode == 6 && resultCode == getActivity().RESULT_OK) {
            if (isLogin) {
                getUnReadMsg();
            }
        }
    }

    private void setUnloginInfo() {
        mTotalAssets.setText("----");
        mTotalProfit.setText("---");
        mYesterdayProfit.setText("---");
        mCoinNum.setText("---");
        mCouponNum.setText("---");
        mInviteCode.setText("-----");
        mRedPacketTxt.setText("---");
        mWalletMoney.setText("---");
        mVaultGrams.setText("---");
        mTitleView.getTitletextView().setText(getString(R.string.main_menu3_txt));
    }

    @Override
    protected void lazyLoad() {
        if (!isPrepared || !isVisible) {
            return;
        }
        if (isLogin) {
            getUnReadMsg();
        }
    }

    public void showUnLoginDialog() {
        if (shareStore == null || getActivity() == null || getActivity().isFinishing()) {
            return;
        }
        if (!shareStore.getBoolean(Strs.IS_LOGIN, false)) {
            if (mLayout.getChildCount() != 2) {
                mLayout.addView(unloginView);
                setUnloginInfo();
            }
        } else {
            if (mLayout.getChildCount() == 2) {
                mLayout.removeView(unloginView);
            }
        }
    }

    private void getUnReadMsg() {
        ActionUtil actionUtil = new ActionUtil(getActivity());
        actionUtil.getUnReadMsg();
        actionUtil.setOnPassBackListener(new OnPassBackListener() {

            @Override
            public void passBack(BaseModel model) {
                if (!isActivityAvailable()) {
                    return;
                }
                MsgInfo msgInfo = (MsgInfo) model;
                if (msgInfo == null) {
                    return;
                }
                int unreadMsgCount = msgInfo.getUnreadMsgCount();
                if (unreadMsgCount != 0) {
                    mTitleView.getNotificationView().setSelected(true);
                } else {
                    mTitleView.getNotificationView().setSelected(false);
                }
            }
        });
    }
}
